//
//  M4HomeViewController.swift
//  M4
//
//  Created by YuChuang on 2024/8/6.
//

import UIKit
import KakaJSON

class M4HomeViewController: M4BaseViewController {
    
    @IBOutlet weak var M4HomeNavView: UIView!
    
    lazy var M4TableHeadView: UIView = {
        let view = UIView()
        view.backgroundColor = .clear
        return view
    }()
    
    lazy var M4HomeTableHeadImage: UIImageView = {
        let img = UIImageView()
        img.image = UIImage(named: "home_banner1")
        return img
    }()
    
    lazy var M4DecriptionView: M4DecriptionStringView = {
        let dv = M4DecriptionStringView(M4IsCheck: true, c: self, M4BtnSelectedStatus: nil)
        return dv
    }()
    
    private var M4HomeData: M4HomeInfoModel?
    
    private var M4Total = 0
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navigationController?.navigationBar.isHidden = true
        M4CreditStausNetAndHomeNet()
    }
    
    var GASQ : Int = 0
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        self.navigationController?.navigationBar.isHidden = false
        
        
        let params: [[String:Any]] = [
            [
                "adga" : 2001,
                "sdqw" : inTime,
                "hgjyj" : Int(Date().timeIntervalSince1970 * 1000) ,
                "GASQ" : GASQ
            ]
        ]
        M4HiddenPointDataManager.M4UploadHiddenPoint(type: .Home, paramsKey: "fasqw", params: params, complete: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        M4NavBarColor = .clear
        
        view.addSubview(M4DecriptionView)
        M4DecriptionView.snp.makeConstraints { make in
            make.left.equalToSuperview().offset(12)
            make.right.equalToSuperview().offset(-12)
            make.bottom.equalToSuperview().offset(-M4TabBarFullHeight()-8)
        }
        
        view.addSubview(M4TableView)
        M4TableView.snp.makeConstraints { make in
            make.left.right.equalToSuperview()
//            make.bottom.equalToSuperview().offset(-M4TabBarFullHeight())
            make.bottom.equalTo(M4DecriptionView.snp.top).offset(-12)
            make.top.equalTo(M4HomeNavView.snp.bottom)
        }
        M4TableView.addSubview(M4HomeTableHeadImage)
        M4HomeTableHeadImage.snp.makeConstraints { make in
            make.top.left.right.equalToSuperview()
            make.width.equalTo(M4ScreenWidth)
            make.height.equalTo(M4ScreenWidth*216/360)
        }
        M4HomeTableHeadImage.layer.zPosition = -1
        M4HomeTableHeadImage.isHidden = true
    M4addRefreshToTaleView { [weak self] in
            self?.M4CreditStausNetAndHomeNet()
        }
        M4VersionNet()
    }
    
    @IBAction func M4Kefuaction(_ sender: UIButton) {
        let alert = M4KFAlertView()
        alert.didTapKFzxHandle = {
            
            
        }
        alert.M4AlertViewShow()
        sender.M4EventUnavailable = false
    }
    
    @IBAction func M4SuggestionAction(_ sender: UIButton) {
        self.navigationController?.pushViewController(M4SuggestionViewController(), animated: true)
        sender.M4EventUnavailable = false
    }
    
    override func M4CellAction(_ action: M4IDAction) {
        let type = M4HomeStatusAction(rawValue: action.M4ActionType)
        if type == .M4HomeFirstAction {
            if M4UserDataManager.m4UserShare.M4Token == "" {
                AppDelegate.M4JumpLoginPage()
            }
            else {
                M4UserDataManager.m4UserShare.M4ProductCode = M4HomeData?.KJg?[0].QFccqUEvct ?? ""
                let product = M4HomeData?.KJg?[0]
                if [1,2,3,4,5,6].contains(product?.HRJAukei) {
                    let page = M4LoanResultViewController()
                    page.M4LoanId = product?.UOqUYNLSQk ?? 0
                    self.navigationController?.pushViewController(page, animated: true)
                    return
                }
                if [7, 8].contains(product?.HRJAukei) {
                    let page = M4PagoDetailViewController()
                    page.M4PagoId = product?.UOqUYNLSQk ?? 0
                    self.navigationController?.pushViewController(page, animated: true)
                    return
                }
                M4JumpPage()
                print("M4HomeFirstAction")
            }
        }
        else if type == .M4HomeSecondAction {
            let proModel = action.M4ActionData as? M4HomeProductModel
            M4UserDataManager.m4UserShare.M4ProductCode = proModel?.QFccqUEvct ?? ""
//            let page = M4LoanResultViewController()
//            self.navigationController?.pushViewController(page, animated: true)
            //0首页 1认证中 2审核中 3审核通过 4审核被拒 5订单异常关闭 6放款失败 7正常待还 8逾期未还
            let m4status = proModel?.HRJAukei ?? 0
            if m4status == 0 || m4status == 1 || m4status == 5 {
                if proModel?.TleRIb == 0 {//不可借
                    //弹框提示
                    let alert = UINib(nibName: "M4ApplyTipAlertView", bundle: nil).instantiate(withOwner: self).last as! M4ApplyTipAlertView
                    alert.M4AlertViewShow()

                }else{
                    M4JumpPage()
                }
            }
            else if m4status == 2 || m4status == 3 || m4status == 4 || m4status == 6 {
                let page = M4LoanResultViewController()
                page.M4LoanId = proModel?.UOqUYNLSQk ?? 0
                self.navigationController?.pushViewController(page, animated: true)
            }
            else if m4status == 7 || m4status == 8 {
                let page = M4PagoDetailViewController()
                page.M4PagoId = proModel?.UOqUYNLSQk ?? 0
                self.navigationController?.pushViewController(page, animated: true)
            }
            print("M4HomeSecondAction")
        }
        else if type == .M4HomeSectionTimeEndAction {
//            M4CreditStausNetAndHomeNet()
            let loading = M4LoadingAlertView()
            loading.M4LoadingAlertShow()
            /* 倒计时结束卡2秒之后再去刷新首页数据 */
            DispatchQueue.main.asyncAfter(wallDeadline: .now()+4) {
                self.M4HomeInfoNet(alert: loading)
            }
        }
    }
    
    override func M4DataRefresh() {
        M4CreditStausNetAndHomeNet()
    }
    
}

extension M4HomeViewController {
    
    private func M4HomeChangeUI(isFirst: Bool) {
        var imageHeight = isFirst ? M4ScreenWidth*216/360 : M4ScreenWidth*170/360
        var headHeight = isFirst ? M4ScreenWidth*216/360-85 : M4ScreenWidth*170/360-27
        var imageName = isFirst ? "home_banner1" : "home_banner"
        if M4UserDataManager.m4UserShare.M4AuditAccount == 1 &&
            self.M4HomeData?.yKsdf == 0{
            imageHeight = M4ScreenWidth*170/360
            headHeight = M4ScreenWidth*170/360-27
            imageName = "home_banner1"
        }
        M4HomeTableHeadImage.image = UIImage(named: imageName)
        M4HomeTableHeadImage.snp.updateConstraints { make in
            make.height.equalTo(imageHeight)
        }
        M4TableHeadView.frame = CGRect(x: 0, y: 0, width: M4ScreenWidth, height: headHeight)
        M4TableView.tableHeaderView = M4TableHeadView
    }
    
    private func M4HomeAddDataSource() {
        M4TableSources.removeAll()
        if M4UserDataManager.m4UserShare.M4AuditAccount == 1 &&
            self.M4HomeData?.yKsdf == 0 {
            M4TableSources.append(M4TableViewCellData("M4HomeFirstCell", XIB: true, M4HomeData?.KJg?[0] ?? M4HomeProductModel()))
        } else {
            if M4Total < 5 {
                M4TableSources.append(M4TableViewCellData("M4HomeFirstCell", XIB: true, M4HomeData?.KJg?[0] ?? M4HomeProductModel()))
            }
            else {
                M4HomeData?.KJg?.forEach({ product in
                    M4TableSources.append(M4TableViewCellData("M4HomeSecondCell", XIB: true, product))
                })
            }
        }
        
        M4TableView.reloadData()
    }
    
}

extension M4HomeViewController {
    
    private func M4HomeInfoNet(alert: M4LoadingAlertView) {
        let parm: [String : Any] = ["ZfOdz": "ESP", "RgiygIhVto": M4UserDataManager.m4UserShare.M4Itemcode, "IHXhPhhLMwA": M4UserDataManager.m4UserShare.M4Token]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4home, .post, params: parm), false) { model in
            self.M4endRefresh()
            alert.M4AlertViewHidden()
            if model.code == 1 {
                self.GASQ = 1
                let data = model.data as? [String : Any]
                self.M4HomeData = data?.kj.model(M4HomeInfoModel.self)
                if self.M4HomeData?.yKsdf == nil {
                    self.M4HomeData?.yKsdf = 0
                }
                self.M4HomeChangeUI(isFirst: self.M4HomeData?.yKsdf == 0 ? true : false)
                self.M4HomeTableHeadImage.isHidden = false
                self.M4HomeAddDataSource()
            }
            else {
                self.GASQ = 0
                self.M4HomeTableHeadImage.isHidden = true
                self.view.makeToast(model.message, position: .center)
            }
        }
    }
    
    private func M4VersionNet() {
        let parm: [String : Any] = ["WusPtnlLWL": "ESP", "VcKV": M4UserDataManager.m4UserShare.M4Itemcode, "GXJFEGIAP": M4UserDataManager.m4UserShare.M4Version, "AnE": 2]
        M4NetworkManager().M4Request(M4NetworkTarget.M4_targetType(.m4version, .post, params: parm), false) { model in
            if model.code == 1 {
                let data = model.data as? [String : Any]
                let isNew = data?["IAUxlYSel"] as? Int ?? 1
                let needReInstall = data?["WuJa"] as? Int ?? 0
                let content = data?["HEHZrSqLUYr"] as? String ?? ""
                let downLoadUrl = data?["XPhU"] as? String ?? ""
                if isNew == 0 {
                    let versionAlert = UINib(nibName: "M4VersionAlertView", bundle: nil).instantiate(withOwner: self).last as? M4VersionAlertView
                    versionAlert?.M4VersionContentLabel.text = content
                    versionAlert?.M4VersionCloseButton.isHidden = needReInstall == 1 ? false : true
                    versionAlert?.M4VersionCloseTop.constant = needReInstall == 1 ? 0 : 20
                    versionAlert?.M4VersionCloseHeight.constant = needReInstall == 1 ? 0 : 29
                    versionAlert?.M4VersionUpdateBlock = {
                        guard let url = URL(string: downLoadUrl) else { return }
                        let open = UIApplication.shared.canOpenURL(url)
                        if open {
                            if #available(iOS 10.0, *) {
                                UIApplication.shared.open(url, options: [:]) { _ in }
                            } else {
                                UIApplication.shared.openURL(url)
                            }
                        }
                    }
                    versionAlert?.M4AlertViewShow()
                }
            }
        }
    }
    
    private func M4CreditStausNetAndHomeNet() {
        let loading = M4LoadingAlertView()
        loading.M4LoadingAlertShow()
        M4PublicNetwork.M4CreditStatusAndInfos(false) { isSuccess in
            self.M4Total = 0
            if isSuccess {
                if M4CreditStatusManager.m4CreditShare.m4personalCredit == "1" && M4CreditStatusManager.m4CreditShare.m4contactCredit == "1" &&  M4CreditStatusManager.m4CreditShare.m4identityCredit == "1" && M4CreditStatusManager.m4CreditShare.m4bankCredit == "1" && M4CreditStatusManager.m4CreditShare.m4faceCredit == "1" {
                    self.M4Total += 5
                }
            }
            self.M4HomeInfoNet(alert: loading)
        }
    }
    
    private func M4JumpPage() {
        M4PublicNetwork.M4CreditStatusAndInfos() { isSuccess in
            if isSuccess {
                var page = M4BaseViewController()
                if M4CreditStatusManager.m4CreditShare.m4LoanCredit == "0" {
                    page = M4CrediteInfoViewController()
                }
                else if M4CreditStatusManager.m4CreditShare.m4personalCredit == "0" {
                    page = M4FirstInfoViewController()
                }
                else if M4CreditStatusManager.m4CreditShare.m4contactCredit == "0" {
                    page = M4SecondInfoViewController()
                }
                else if M4CreditStatusManager.m4CreditShare.m4identityCredit == "0" {
                    page = M4ThirdInfoViewController()
                }
                else if M4CreditStatusManager.m4CreditShare.m4bankCredit == "0" {
                    page = M4FourInfoViewController()
                }
                else if M4CreditStatusManager.m4CreditShare.m4faceCredit == "0" {
                    page = M4FiveInfosViewController()
                }
                else {
                    M4LimitVerification().M4LimitDataAsk1 { arrayCount in
                        if arrayCount.count > 0 {
                            M4LimitVerification().M4_showAskAlert(arr: arrayCount) { _ in }
                        }
                        else {
                            //检查/上传埋点，跳转提单页
                            M4PublicNetwork.M4CheckNeedUpload { t in
                                if t == 1 {
                                    if M4UserDataManager.M4HasShowUploadPage == false {
                                        M4PublicNetwork.M4ShowUploadAlert { r in
                                            if r == true {
                                                for c in self.navigationController?.children ?? [] {
                                                    if c is M4ProductDetailViewController {
                                                        return
                                                    }
                                                }
                                                let page = M4ProductDetailViewController()
                                                self.navigationController?.pushViewController(page, animated: true)
                                            }
                                        }
                                    } else {
                                        M4PublicNetwork.M4ShowUploadAlert { r in
                                            if r == true {
                                                for c in self.navigationController?.children ?? [] {
                                                    if c is M4ProductDetailViewController {
                                                        return
                                                    }
                                                }
                                                let page = M4ProductDetailViewController()
                                                self.navigationController?.pushViewController(page, animated: true)
                                            }
                                        }
                                    }
                                } else {
                                    for c in self.navigationController?.children ?? [] {
                                        if c is M4ProductDetailViewController {
                                            return
                                        }
                                    }
                                    let page = M4ProductDetailViewController()
                                    self.navigationController?.pushViewController(page, animated: true)
                                }
                            }
                            
                          /*
                           if M4UserDataManager.M4HasShowUploadPage == false {
                               let uploadController = M4UploadController()
                               uploadController.M4UploadResult = { r in
                                   if r == true {
                                       let page = M4ProductDetailViewController()
                                       self.navigationController?.pushViewController(page, animated: true)
                                   }
                               }
                               self.navigationController?.pushViewController(uploadController, animated: true)
                           } else {
                               let loading = M4LoadingAlertView()
                               loading.M4LoadingAlertShow()
                               M4PublicNetwork.M4VerficationPointDataNet { issuccess in
                                   loading.M4AlertViewHidden()
                                   if issuccess {
                                       let page = M4ProductDetailViewController()
                                       self.navigationController?.pushViewController(page, animated: true)
                                   }
                               }
                           }
                           */
                        }
                    }
                    return
                }
                self.navigationController?.pushViewController(page, animated: true)

            }
        }
    }
}


extension M4HomeViewController {
    class func M4InfoController(r: @escaping (M4BaseViewController?)->Void)  {
        M4PublicNetwork.M4CreditStatusAndInfos() { isSuccess in
            if isSuccess {
                var page: M4BaseViewController?
                if M4CreditStatusManager.m4CreditShare.m4LoanCredit == "0" {
                    page = M4CrediteInfoViewController()
                }
                else if M4CreditStatusManager.m4CreditShare.m4personalCredit == "0" {
                    page = M4FirstInfoViewController()
                }
                else if M4CreditStatusManager.m4CreditShare.m4contactCredit == "0" {
                    page = M4SecondInfoViewController()
                }
                else if M4CreditStatusManager.m4CreditShare.m4identityCredit == "0" {
                    page = M4ThirdInfoViewController()
                }
                else if M4CreditStatusManager.m4CreditShare.m4bankCredit == "0" {
                    page = M4FourInfoViewController()
                }
                else if M4CreditStatusManager.m4CreditShare.m4faceCredit == "0" {
                    page = M4FiveInfosViewController()
                }
                r(page)
            }
        }
    }
}
